// routes/userRoutes.js
const express = require('express');
const router = express.Router();
const userControll = require('../controllers/userControll');
const pool = require('../config/db'); // 导入数据库连接池
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const { expressjwt: expressJwt } = require('express-jwt');
const jwtBlacklistControll = require('../controllers/jwtBlacklistControll');

const key = "Yangjunjwt123456"; // 秘钥
// // JWT 黑名单检查中间件
// const blacklistCheck = async (req, payload, done) => {
//     const token = req.headers.authorization.split(' ')[1];
//     const isBlacklisted = await jwtBlacklistControll.isTokenBlacklisted(token);
  
//     if (isBlacklisted) {
//       return done(null, true); // Token is blacklisted
//     }
//     done();
//   };
// JWT 黑名单检查中间件
// const blacklistCheck = async (req, payload, done) => {
//     const token = req.headers.authorization.split(' ')[1];
//     const isBlacklisted = await jwtBlacklistControll.isTokenBlacklisted(token);

//     if (isBlacklisted) {
//         return done(null, true); // Token is blacklisted
//     }
//     return done(null, false);
// };
// // 获取用户通过ID
// router.get('/:id', expressJwt({ secret: key, algorithms: ['HS256'] }), async (req, res) => {
//     try {
//       const user = await userControll.getUserById(req.params.id);
//       if (user) {
//         res.json(user);
//       } else {
//         res.status(404).json({ message: '用户不存在' });
//       }
//     } catch (error) {
//       res.status(500).json({ message: error.message });
//     }
//   });

// 获取用户通过ID
// router.get('/:id', expressJwt({ secret: key, algorithms: ['HS256'], isRevoked: blacklistCheck }), async (req, res) => {
    router.get('/:id', expressJwt({ secret: key, algorithms: ['HS256'] }), async (req, res) => {
    try {
      const user = await userControll.getUserById(req.params.id);
      if (user) {
        res.json(user);
      } else {
        res.status(404).json({ message: '用户不存在' });
      }
    } catch (error) {
      if (error.name === 'UnauthorizedError') {
        // 将无效的 JWT 添加到黑名单中
        const token = req.headers.authorization.split(' ')[1];
        await jwtBlacklistControll.addTokenToBlacklist(token);
        res.status(401).json({ message: '未携带token或token失效' });
      } else {
        res.status(500).json({ message: error.message });
      }
    }
  });
  // 更新用户信息
// router.put('/:id', expressJwt({ secret: key, algorithms: ['HS256'], isRevoked: blacklistCheck }), async (req, res) => {
    router.put('/:id', expressJwt({ secret: key, algorithms: ['HS256']}), async (req, res) => {
    try {
      const { username, email, password } = req.body;
      const user = await userControll.getUserById(req.params.id);
      if (!user) {
        return res.status(404).json({ message: '用户不存在' });
      }
      await userControll.updateUser(req.params.id, username, email, password);
      const updatedUser = await userControll.getUserById(req.params.id);
      res.json(updatedUser);
    } catch (error) {
      if (error.name === 'UnauthorizedError') {
        // 将无效的 JWT 添加到黑名单中
        const token = req.headers.authorization.split(' ')[1];
        await jwtBlacklistControll.addTokenToBlacklist(token);
        res.status(401).json({ message: '未携带token或token失效' });
      } else {
        res.status(500).json({ message: error.message });
      }
    }
  });
  
  // 删除用户
//   router.delete('/:id', expressJwt({ secret: key, algorithms: ['HS256'], isRevoked: blacklistCheck }), async (req, res) => {
    router.delete('/:id', expressJwt({ secret: key, algorithms: ['HS256'] }), async (req, res) => {
    try {
      const user = await userControll.getUserById(req.params.id);
      if (!user) {
        return res.status(404).json({ message: '用户不存在' });
      }
      await userControll.deleteUser(req.params.id);
      res.json({ message: '用户已删除' });
    } catch (error) {
      if (error.name === 'UnauthorizedError') {
        // 将无效的 JWT 添加到黑名单中
        const token = req.headers.authorization.split(' ')[1];
        await jwtBlacklistControll.addTokenToBlacklist(token);
        res.status(401).json({ message: '未携带token或token失效' });
      } else {
        res.status(500).json({ message: error.message });
      }
    }
  });
// 其他用户相关路由...
// 用户注册
// router.post('/register', async (req, res) => {
//     try {
//       const { username, email, password } = req.body;
  
//       // 检查是否已经存在同名用户或相同邮箱
//       const existingUser = await pool.query('SELECT * FROM users WHERE username = ? OR email = ?', [username, email]);
//       if (existingUser[0].length > 0) {
//         return res.status(400).json({ message: 'Username or email already exists' });
//       }
     
//       const result = await userControll.createUser(username, email, password);
//       const userId = result.insertId;
//       const newuser = await userControll.getUserById(userId);
//       res.status(201).json(newuser);
//     } catch (error) {
//       res.status(500).json({ message: error.message });
//     }
//   });
  router.post('/register', async (req, res) => {
    try {
      const { username, email, password } = req.body;
  
      // 检查是否已经存在同名用户或相同邮箱
      const [existingUser] = await pool.query('SELECT * FROM users WHERE username = ? OR email = ?', [username, email]);
      if (existingUser.length > 0) {
        return res.status(400).json({ message: '用户名或邮箱已存在' });
      }
  
      const result = await userControll.createUser(username, email, password);
      const userId = result.insertId;
      const newUser = await userControll.getUserById(userId);
      res.status(201).json(newUser);
    } catch (error) {
      res.status(500).json({ message: error.message });
    }
  });
  
  // 用户登录
  router.post('/login', async (req, res) => {
    try {
      const { email, password } = req.body;
  
      // 获取用户
      const [userRows] = await pool.query('SELECT * FROM users WHERE email = ?', [email]);
      const user = userRows[0];
  
      if (!user) {
        return res.status(400).json({ message: '用户不存在' });
      }
  
      // 验证密码
      const isPasswordValid = await bcrypt.compare(password, user.password);
      if (!isPasswordValid) {
        return res.status(400).json({ message: '请输入正确的密码' });
      }
   // 生成 JWT
   const token = jwt.sign({ userId: user.user_id, username: user.username }, key, { expiresIn: '1h' });
   res.json({ token, message: '后台登录成功' });
    //   res.json({ message: 'Login successful' });
    } catch (error) {
      res.status(500).json({ message: error.message });
    }
  });
module.exports = router;
